package com.xflib.framework.util;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * logback 工具
 */
public class logbackUtil {

    public static void init(String filePath){
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        String logbackConfigPath = filePath;
        File file = new File(logbackConfigPath);
        if(!file.exists()) {
            System.out.println("logbackConfigPath file is no exist");
            System.exit(2);
        } else if (!file.isFile()) {
            System.out.println("logbackConfigPath file is not a file");
            System.exit(3);
        } else if (!file.canRead()) {
            System.out.println("logbackConfigPath file can not read");
            System.exit(4);
        }
        JoranConfigurator joranConfigurator = new JoranConfigurator();
        joranConfigurator.setContext(loggerContext);
        loggerContext.reset();
        try {
            joranConfigurator.doConfigure(file);
        } catch (Exception e) {
            System.out.println("logbackConfigPath Load logback config file error. Message: " + e.getMessage());
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);

    }

    /**
     * 动态设置指定package日志级别
     * @param level ALL TRACE DEBUG INFO WARN ERROR OFF
     * @param packageName root 为全局
     */
    public static void updateLogbackLevel( String level, String packageName) {
        LoggerContext loggerContext =(LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.getLogger(packageName).setLevel(Level.toLevel(level));
    }

    /**
     * 动态设置全局日志级别
     * @param level
     */
    public static void updateLogbackLevel( String level) {
        updateLogbackLevel(level,"root");
    }

    /**
     * 动态设置指定类 clazz 所在包的日志级别
     * @param level
     * @param clazz Class
     */
    public static void updateLogbackLevel( String level, Class clazz) {
        updateLogbackLevel(level, clazz.getName());
    }
}
